import uploadFile from '../../utils/uploadImage'
var productId
var releatedId
var width
var height
var free
var category

Page({
  data: {
    devicePosition: 'back',
    orderId: null
  },

  onLoad: function (options) {
    this.ctx = wx.createCameraContext()
    productId = options.productId
    releatedId = options.releatedId
    width = options.width
    height = options.height
    free = options.free
    category = options.category
    if (options.orderId) {
      this.data.orderId = options.orderId
    }
  },

  cameraInit: function () {},

  handleCameraError: function () {
    wx.showToast({
      title: '用户拒绝使用摄像头',
      icon: 'none',
    })
  },

  reverseCamera: function () {
    if (category === 'receipt') {
      wx.showToast({
        icon: 'none',
        title: '回执相片请使用后置摄像头拍摄',
      })
    } else {
      this.setData({
        devicePosition: 'back' === this.data.devicePosition ? 'front' : 'back',
      })
    }
  },

  takePhoto: function () {
    //拍摄照片
    this.ctx.takePhoto({
      quality: 'high',
      success: async (res) => {
        let tempFilePath = res.tempImagePath
        const originalImageUrl = await uploadFile(tempFilePath).catch((err) => {
          console.log(err)
          wx.showToast({
            title: '上传图片失败',
            icon: 'error',
          })
        })
        if (originalImageUrl) {
          if (width != null) {
            wx.redirectTo({
              url: `/pages/photoDetect/photoDetect?originalImagePath=${tempFilePath}&releatedId=${releatedId}&productId=${productId}&originalImageUrl=${originalImageUrl}&height=${height}&width=${width}&free=${free}&category=${category}`,
            })
          } else {
            wx.redirectTo({
              url: `/pages/photoDetect/photoDetect?originalImagePath=${tempFilePath}&releatedId=${releatedId}&productId=${productId}&originalImageUrl=${originalImageUrl}&category=${category}&orderId=${this.data.orderId ?? ''}`,
            })
          }
        }
      },
      fail: (res) => {
        //拍摄失败
      },
    })
  },

  onShow: function () {
    wx.getSetting({
      success: (res) => {
        if (res.authSetting['scope.camera']) {
          this.setData({
            authCamera: true,
          })
        } else {
          this.setData({
            authCamera: false,
          })
        }
      },
    })
  },

  cancel() {
    wx.navigateBack()
  },
})
